#include "rpc/server_processor.h"
#include "include/rpc_helper.h"
#include "rpc/buffer.h"
#include "rpc/rpc_util.h"

namespace urpc {

void ServerProcessor::HandleRead(Connection* conn, Buffer* buf) {
  CHECK(conn != NULL && buf != NULL);
  RpcHeader* bhs = (RpcHeader*) buf->Read(HEADER_LENGTH);

  Handler* handler = handler_map_->FindHandlerById(bhs->func_id);
  CHECK(handler != NULL) << "function id: " << bhs->func_id;
  scoped_ptr<Message> request(handler->request->New());
  bool parse_ok = request->ParseFromArray(buf->Read(bhs->length), bhs->length);
  if (!parse_ok) {
    LOG(WARNING) << "parse message from array error, msg: "
                 << request->DebugString();
    return;
  }

  scoped_ptr<Message> response(handler->response->New());
  SenderClosure done(response.get(), conn, bhs->id);
  handler->service->CallMethod(handler->method_descriptor, NULL, request.get(),
                               response.get(), &done);
}

}
